using UnityEngine;
using System.Collections;
using LogicalComponent.util;
using LogicalComponent.rules.grid;

public class Stepper : MonoBehaviour, MoveUtil.Mover {

    public Coordinate Position;
    public Coordinate Destination;

    public float MoveDelay = 1;
    private float moveTimer = 0;
    private int step = 0;
    public float offset = 0f;

    private MoveRulesUI moveRules;

    private Path p;

    void Start()
    {
        moveRules = GameObject.FindGameObjectWithTag("game_manager").GetComponent<MoveRulesUI>();
        if (UiUtil.GetTile(Position) != null)
        {
            MoveUtil.Teleport(Position, this.transform);
        }
        Vector3 temp = new Vector3(this.transform.position.x, this.transform.position.y + offset, this.transform.position.z);
        this.transform.position = temp;
        this.Reset();
    }

    private void Reset()
    {
        step = 1;
        p = null;
        moveTimer = 0;
    }

    public void DoMove(float timePassed)
    {
        if(Destination == Position)
        {
            return;
        }

        if (p == null)
        {
            SearchAlgorithm search = new AStarSearch(
                this.moveRules.RuleSet, this.Position,  this.Destination);
            search.DoSearch();
            p = search.GetPathTo(this.Destination);
        }

        if(moveTimer < MoveDelay)
        {
            moveTimer += timePassed;
        }
        else if(moveTimer >= MoveDelay)
        {
            moveTimer = moveTimer - MoveDelay;
            this.TakeStep();
        }
    }

    public void SetDestination(Coordinate c)
    {
        Reset();
        Destination = c;
    }

    private void TakeStep()
    {
        Coordinate thisStep = p.GetCoordinate(step);
        MoveUtil.Teleport(thisStep, this.transform);
        this.Position = thisStep;
        step++;
        Vector3 temp = new Vector3(this.transform.position.x, this.transform.position.y + offset, this.transform.position.z);
        this.transform.position = temp;
    }
}
